import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_swiper_plus/flutter_swiper_plus.dart';
import 'package:gw_github_flutter/common/global.dart';
import 'package:gw_github_flutter/common/route_name.dart';
import 'package:gw_github_flutter/models/tbSectionModel.dart';
import 'package:gw_github_flutter/tools/gwEasyRefrashManager.dart';
import 'package:gw_github_flutter/tools/gwGetManager.dart';
import 'package:sticky_and_expandable_list/sticky_and_expandable_list.dart';

class SliverRouteTableViewAppBar extends StatefulWidget {
  SliverRouteTableViewAppBar({Key? key}) : super(key: key);

  @override
  State<SliverRouteTableViewAppBar> createState() =>
      _SliverRouteTableViewAppBarState();
}

class _SliverRouteTableViewAppBarState
    extends State<SliverRouteTableViewAppBar> {
  var list = Global.getTBSectionsList();
  late EasyRefreshController _controller;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(child: Scaffold(body: customBody()));
  }

  Widget customBody() {
    return EasyRefresh.builder(
        controller: _controller,
        header: GwEasyRefrashManager.setRefrashHeader(
            mainAxisAlignment: MainAxisAlignment.center),
        footer: GwEasyRefrashManager.setRefrashFooter(
            mainAxisAlignment: MainAxisAlignment.center),
        onLoad: () async {
          await Future.delayed(const Duration(seconds: 2));
          if (!mounted) {
            return;
          }
          _controller.finishLoad(IndicatorResult.noMore);
        },
        onRefresh: () async {
          await Future.delayed(const Duration(seconds: 2));
          if (!mounted) {
            return;
          }
          setState(() {
            list = list;
          });
          _controller.finishRefresh();
          _controller.resetFooter();
        },
        childBuilder: (context, physics) {
          return CustomScrollView(
            physics: physics,
            slivers: <Widget>[
              SliverAppBar(
                pinned: true,
                floating: false,
                expandedHeight: 200,
                flexibleSpace: FlexibleSpaceBar(
                  title: Text(
                    "Sliver Example",
                    style: TextStyle(color: Colors.white),
                  ),
                ),
                iconTheme: IconThemeData(color: Colors.white),
              ),
              const HeaderLocator.sliver(),
              SliverToBoxAdapter(
                  child: 
                  Swiper(
                layout: SwiperLayout.CUSTOM,
                customLayoutOption: CustomLayoutOption(
                        startIndex: -1, stateCount: 3)
                    .addRotate([-45.0 / 180, 0.0, 45.0 / 180]).addTranslate([
                  new Offset(-370.0, -40.0),
                  new Offset(0.0, 0.0),
                  new Offset(370.0, -40.0)
                ]),
                itemWidth: 300.0,
                itemHeight: 200.0,
                itemBuilder: (context, index) {
                  return Container(
                    color: Colors.grey,
                    child:  Center(
                      child: Text("$index"),
                    ),
                  );
                },
                itemCount: 10,
                pagination:SwiperPagination(
                  alignment: Alignment.center,
                  builder: RectSwiperPaginationBuilder(
                    activeColor: Colors.red,
                    color: Colors.yellow,
                    size: Size(2,3),
                    activeSize: Size(2,4)
                  )
                  ),
                // control: SwiperControl(),
              )
              ),
              SliverExpandableList(
                builder: SliverExpandableChildDelegate<dynamic, TbSectionModel>(
                    sectionList: list,
                    sectionBuilder: (context, containerInfo) =>
                        AnimationSectionWidget(
                          section: list[containerInfo.sectionIndex],
                          containerInfo: containerInfo,
                          onStateChanged: () {
                            //notify ExpandableListView that expand state has changed.
                            WidgetsBinding.instance.addPostFrameCallback((_) {
                              if (mounted) {
                                setState(() {});
                              }
                            });
                          },
                        ),
                    itemBuilder: (context, sectionIndex, itemIndex, index) {
                      String item = list[sectionIndex].items?[itemIndex];
                      return ListTile(
                        leading: CircleAvatar(
                          child: Text("$index"),
                        ),
                        title: Text(item),
                      );
                    }),
              ),
              const FooterLocator.sliver()
            ],
          );
        });
  }
}

class AnimationSectionWidget extends StatefulWidget {
  final TbSectionModel section;
  final ExpandableSectionContainerInfo containerInfo;
  final VoidCallback onStateChanged;

  AnimationSectionWidget(
      {required this.section,
      required this.containerInfo,
      required this.onStateChanged});

  @override
  __SectionWidgetState createState() => __SectionWidgetState();
}

class __SectionWidgetState extends State<AnimationSectionWidget>
    with SingleTickerProviderStateMixin {
  static final Animatable<double> _halfTween =
      Tween<double>(begin: 0.0, end: 0.5);
  late AnimationController _controller;

  late Animation _iconTurns;

  late Animation<double> _heightFactor;

  @override
  void initState() {
    super.initState();
    _controller =
        AnimationController(vsync: this, duration: Duration(milliseconds: 300));
    _iconTurns =
        _controller.drive(_halfTween.chain(CurveTween(curve: Curves.easeIn)));
    _heightFactor = _controller.drive(CurveTween(curve: Curves.easeIn));

    if (widget.section.isSectionExpanded()) {
      _controller.value = 1;
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    widget.containerInfo
      ..header = _buildHeader(context)
      ..content = _buildContent(context);
    return ExpandableSectionContainer(
      info: widget.containerInfo,
    );
  }

  Widget _buildHeader(BuildContext context) {
    return Container(
      color: Colors.lightBlue,
      child: ListTile(
        title: Text(
          widget.section.header ?? "",
          style: TextStyle(color: Colors.white),
        ),
        trailing: RotationTransition(
          turns: _iconTurns as Animation<double>,
          child: const Icon(
            Icons.expand_more,
            color: Colors.white70,
          ),
        ),
        onTap: _onTap,
      ),
    );
  }

  void _onTap() {
    widget.section.setSectionExpanded(!widget.section.isSectionExpanded());
    if (widget.section.isSectionExpanded()) {
      widget.onStateChanged();
      _controller.forward();
    } else {
      _controller.reverse().then((_) {
        widget.onStateChanged();
      });
    }
  }

  Widget _buildContent(BuildContext context) {
    return SizeTransition(
      sizeFactor: _heightFactor,
      child: SliverExpandableChildDelegate.buildDefaultContent(
          context, widget.containerInfo),
    );
  }
}
